package logic

import (
	"context"
	"errors"
	"hippo-fresh/model/mysql"

	"hippo-fresh/hipporpc/hipporpc"
	"hippo-fresh/hipporpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopAddLogic) ShopAdd(in *hipporpc.ShopAddRequest) (*hipporpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line

	var class mysql.Class
	mysql.DB.Debug().Where("name = ?", in.ClassName).Find(&class)
	if class.ID == 0 {
		m := mysql.Class{
			Name: in.ClassName,
		}
		mysql.DB.Debug().Create(&m)
	}

	var shops mysql.Shop
	mysql.DB.Debug().Where("title = ?", in.Title).Find(&shops)
	if shops.ID != 0 {
		return nil, errors.New("当前商品已存在，请更换")
	}

	shop := mysql.Shop{
		Title:   in.Title,
		Price:   float64(in.Price),
		Address: in.Address,
		ClassID: int(class.ID),
	}

	mysql.DB.Debug().Create(&shop)

	return &hipporpc.ShopAddResponse{
		ShopId: int64(shop.ID),
	}, nil
}
